<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');
/**
 * Copyright (c) 2010, must art
 *All rights reserved.
 *
 *Redistribution and use in source and binary forms, with or without
 *modification, are permitted provided that the following conditions are met:
 *    * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *    * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *    * Neither the name of the <organization> nor the
 *      names of its contributors may be used to endorse or promote products
 *      derived from this software without specific prior written permission.
 *
 *THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 *ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 *WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *DISCLAIMED. IN NO EVENT SHALL must art BE LIABLE FOR ANY
 *DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 *(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * PHP version 5
 * @copyright  must art 2010
 * @author     Jan Philipp Pietrzyk <programming@must-art.de>
 * @package    
 * @license    BSD
 * @filesource
 */
class ModuleMAYoutubeUserUpload extends Module {
	protected $strTemplate = 'mod_maytuserupload';
	
	public function generate() {
		if (TL_MODE == 'BE')
		{
			$objTemplate = new BackendTemplate('be_wildcard');
			$objTemplate->wildcard = '### Youtube User Upload ###';
			$objTemplate->title = $this->headline;
			$objTemplate->id = $this->id;
			$objTemplate->link = $this->name;
			$objTemplate->href = 'typolight/main.php?do=modules&amp;act=edit&amp;id=' . $this->id;
			return $objTemplate->parse();
		}

		return parent::generate();
	}
	public function compile() {
		$userId = 0;
		//print_r($this);
		
		if($this->protected) {
			$isAllowed = false;
			$this->import('FrontendUser', 'User');
			$groups = deserialize($this->groups);
			if(FE_USER_LOGGED_IN) {
				$userId = $this->User->__get('id');
				if(is_array($groups) && count($groups) > 0) {
					foreach($groups as $group) {
						if($this->User->isMemberOf($group)) {
							$isAllowed = true;
						}
					}
				} else {
					$isAllowed = true;			
				}
			
			}
			if( BE_USER_LOGGED_IN) {
				$isAllowed = true;
			}
			//echo 'bin gesichert'; print_r(get_defined_constants());
			
			if(!$isAllowed) {
				$this->Template->protected = true;
				return;
			}
			
		}
		$this->import('BackendMAYoutubeApiConnector', 'maytBridge');
		//echo $userId;
		
		// Create fields, with rgxp as far as possible
		$arrFields = array();
		$arrFields['mayt_title'] = array
			(
				'name' => 'mayt_title',
				'label' => $GLOBALS['TL_LANG']['MSC']['mayt_title'],
				'inputType' => 'text',
				'eval' => array('rgxp'=>'alnum', 'mandatory'=>true, 'maxlength'=>128, 'decodeEntities'=>true)
		);
		$arrFields['mayt_tags'] = array
			(
				'name' => 'mayt_tags',
				'label' => $GLOBALS['TL_LANG']['MSC']['mayt_tags'],
				'inputType' => 'text',
				'eval' => array('rgxp'=>'extnd', 'mandatory'=>true, 'maxlength'=>128, 'decodeEntities'=>true)
		);
		$arrFields['mayt_description'] = array
			(
				'name' => 'mayt_description',
				'label' => $GLOBALS['TL_LANG']['MSC']['mayt_description'],
				'inputType' => 'textarea',
				'eval' => array('mandatory'=>true)
		);
		$arrFields['mayt_category'] = array
				(
				'name' => 'mayt_category',
				'label' => $GLOBALS['TL_LANG']['MSC']['mayt_category'],
				'inputType' => 'select',
				'options' => $this->maytBridge->getCategorys($this->mayt_categorys,''),
				'eval' => array('mandatory'=>true, )
		);
				
		$arrWidgets = array();
		$doNotSubmit = false;
		// Initialize widgets
		foreach ($arrFields as $arrField)
		{
			$strClass = $GLOBALS['TL_FFL'][$arrField['inputType']];
	
			// Continue if the class is not defined
			if (!$this->classFileExists($strClass))
			{
				continue;
			}
		
			$arrField['eval']['required'] = $arrField['eval']['mandatory'];
			$objWidget = new $strClass($this->prepareForWidget($arrField, $arrField['name'], $arrField['value']));

			// Validate widget
			if ($this->Input->post('FORM_SUBMIT') == 'mayt_step1')
			{
				$objWidget->validate();
	
				if ($objWidget->hasErrors())
				{
					$doNotSubmit = true;
				}
			}
			$arrWidgets[] = $objWidget;
		}
		global $objPage;
		$ytStatus = $this->Input->get('status');
		
		// Case 3: Upload happened - Check for Errors and redirect
		if(strlen($ytStatus)) {
			$this->makeCheckAndUpdateDatabase($arrWidgets, $objPage, $userId);
			
		}
		// Case 2: Input was correct, present submit Form
		elseif($doNotSubmit == false && $this->Input->post('FORM_SUBMIT') == 'mayt_step1') {
			$this->makeUploadFormAndSaveToSession($arrWidgets, $objPage, $userId);
		} 
		// Case 1: Present User Input fields
		else {
			$this->makeMetaForm($arrWidgets, $objPage, $userId);
		}
		
		
		
	
	}
	
	//Details Changed and I need this for a Subclass!
	protected function success($id) {}
	//If Details Change here is a place to subcalss
	protected function makeMetaForm($arrWidgets, $objPage, $userId) {
		$formTemplate = new FrontendTemplate('form_maytform');
		$formTemplate->submit = $GLOBALS['TL_LANG']['MSC']['mayt_submit'];
		$formTemplate->action = $this->generateFrontendUrl($objPage->row());
		$formTemplate->fields = $arrWidgets;
		$this->Template->form = $formTemplate->parse();	
	}
	protected function makeUploadFormAndSaveToSession($arrWidgets, $objPage, $userId) {
		$this->Session->set('mayt_title', $this->Input->post('mayt_title'));
		$this->Session->set('mayt_tags', $this->Input->post('mayt_tags'));
		$this->Session->set('mayt_description', $this->Input->post('mayt_description'));
		$this->Session->set('mayt_category', $this->Input->post('mayt_category'));
		//print_r($this->Session);
		$token = $this->maytBridge->getUploadUrlAndToken(
													$this->Input->post('mayt_title'),
													$this->Input->post('mayt_tags'),
													$this->Input->post('mayt_description'), 
													$this->Input->post('mayt_category'),
													$this->mayt_private
												);
		$formTemplate = new FrontendTemplate('mayt_upload');
		$formTemplate->nextUrl = $this->Environment->__get('url').$this->Environment->__get('requestUri');
		$formTemplate->postUrl = $token['url'];
		$formTemplate->tokenValue = $token['token'];
		$formTemplate->submitValue = $GLOBALS['TL_LANG']['MSC']['mayt_videoUpload'];
		$this->Template->form = $formTemplate->parse();
		
	
	}
	protected function makeCheckAndUpdateDatabase($arrWidgets, $objPage, $userId) {
		$ytId = $this->Input->get('id');
		$ytCode = $this->Input->get('code');
		$this->Database->prepare('INSERT INTO tl_mayac_videos (`id`,`tstamp`, `ytId`, `userId`, `title`,`description`,`tags`,`category` ) VALUES (\'\',  ?, ?, ?, ?, ?, ?,?)')
			->execute(time(),$ytId, $userId, $this->Session->get('mayt_title'),
								$this->Session->get('mayt_description'),
								$this->Session->get('mayt_tags'),
								$this->Session->get('mayt_category')
					);
			//Case Success
		if(strlen($ytId)) {
			//redirect to jumpTo
			//Ich brauche dieechte ID!
			$id = $this->Database->prepare('SELECT id FROM tl_mayt_videos WHERE ytId=?')->Limit(1)->execute($ytId)->row();
			$this->success($id['id']);
			if($this->jumpTo > 0) {	
				$jumpToPage = $this->Database->prepare('SELECT * FROM tl_page WHERE id=?')->Limit(1)->
												execute($this->jumpTo)->row();
				$this->redirect($this->generateFrontendUrl($jumpToPage));
			} else {
				$this->makeMetaForm($arrWidgets, $objPage);
			}
		} 
		//Case Failure
		else {
			$this->Template->form = $GLOBALS['TL_LANG']['MSC']['mayt_error_'.$ytCode];
		}
	}
}
?>